package org.geektimes.configuration.microprofile.config.source.servlet;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.configuration.microprofile.config.DefaultConfigProviderResolver;
import org.geektimes.configuration.microprofile.config.source.servlet.ServletContextPropertiesConfigSource;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @see ServletConfigInitializer
 */
public class ServletContextConfigInitializer implements ServletContextListener {
    public final static String SERVLET_CONTEXT_CONFIG = "SERVLET_CONTEXT_CONFIG";
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        ServletContextPropertiesConfigSource servletContextPropertiesConfigSource = new ServletContextPropertiesConfigSource(servletContext);
        ClassLoader classLoader = servletContext.getClassLoader();
        ConfigProviderResolver configProviderResolver = DefaultConfigProviderResolver.instance();
        ConfigBuilder configBuilder = configProviderResolver.getBuilder();
        configBuilder.forClassLoader(classLoader);

        configBuilder.addDefaultSources();
        configBuilder.addDiscoveredSources();
        configBuilder.addDiscoveredConverters();
        configBuilder.withSources(servletContextPropertiesConfigSource);

        Config config = configBuilder.build();
        configProviderResolver.registerConfig(config, classLoader);
        servletContext.setAttribute(SERVLET_CONTEXT_CONFIG, config);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
